<template>
	<view>
		<ScrollPage @scrolltolower="nextPage">
			<template #content>
				<view>
					<!-- 搜索条件 -->
					<view class="w100" style="padding: 10px 15px 25px 15px">
						<up-form labelPosition="left" labelWidth="110" labelAlign="right">
							<up-form-item label="昵称：">
								<up-input border="surround" v-model="query.nickname" clearable></up-input>
							</up-form-item>
							<up-form-item label="创建时间：">
								<view class="w100 relative">
									<up-input border="surround"  v-model="query.date"></up-input>
									<view class="hw100  bg-transparency absolute" style="height: 40px; left:0; top:0;" @click="showPicker"></view>
								</view>
							</up-form-item>
							<up-form-item label="审核状态：">
								<view class="w100 relative">
									<up-input border="surround"  v-model="statusSelectedName"></up-input>
									<view class="hw100  bg-transparency absolute" style="height: 40px; left:0; top:0;" @click="statusShow"></view>
								</view>
							</up-form-item>
						</up-form>
						<view class="w100 text-center">
							<button class="cu-btn line-gray" @click="searchClean">
								<text class="iconfont icon-delete margin-right-10"></text> 
								<text>重<text class="padding-lr-20"></text>置</text>
							</button>
							<text class="padding-lr-20"></text>
							<button class="cu-btn line-keyblue " @click="confirmSearch">
								<text class="iconfont icon-sousuo margin-right-10"></text> 
								<text>搜<text class="padding-lr-20"></text>索</text>
							</button>
						</view>
					</view>
					<!-- 内容区 -->
					<template v-if="dataList.length > 0">
						<view class="outline">
							<template v-for="(item,index) in dataList" :key="item.userId">
								<view  class="flex-row  row " style="padding: 15px 5px;">
									<!-- 左边 -->	
									<view class="flex-col">
										<MeImage @click="previewSingleImage(item.avatarUrl)"  :src="item.avatarUrl" width="48px" height="48px" radius="5"></MeImage >
										<MeImage   :src="item.nationalFlagUrl" width="48px" height="48px"  mode="aspectFit"></MeImage >
									</view>
									<!-- 右边 -->
									<view class="flex-col flex-sub relative" style="margin-left: 10px;">
										<view class="absolute padding-10 text-gray font-s15 " style="top: 5px;right: 5px;">
                                           <text>{{ index + 1 }}</text>
										</view>
										<view>
											<text class="text-bold">昵称:</text>
											<text class="margin-left-10 font-s36 text-lightGreyblue text-bold">{{item.nickname}}</text>
										</view>
										<view v-if="item.nationality" class="margin-tb-5" >
											<text class="text-bold">国籍:</text>
											<text class="margin-left-10 ">{{item.nationality}}</text>
											<text class="margin-left-10 text-gray font-s22">({{item.countryCode}})</text>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">用户ID:</text>
											<text class="margin-left-10">{{item.userId}}</text>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">生日:</text>
											<text class="margin-left-10">{{item.birthday}}</text>
										</view>
										<view class="flex-col  margin-tb-5 w100" >
											<text class="text-bold ">简介</text>
											<text class=" text-indent text-justify lh-105 text-gray51  margin-tb-10 padding-10 radius-10">{{item.biography}}</text>
										</view>
										<view class="flex-col  margin-tb-5 w100" >
											<text class="text-bold ">脸部照片</text>
											<view class="flex-row flex-wrap margin-tb-10">
												<template v-for="faceUrl in item.faceUrls">
													<view class="margin-10">
														<MeImage  @click="previewSingleImage(faceUrl)" :src="faceUrl" width="148px" height="148px" radius="5"></MeImage >
													</view>
												</template>
											</view>
										</view>
										<view class="flex-col  margin-tb-5 w100" >
											<text class="text-bold ">视频</text>
											<view class="flex-col margin-tb-10" style="width: 148px; height: 148px" @click="toPlay(item.videoUrl, item.posterUrl)">
												<template v-if="item.posterUrl" >
													<view style="width: 148px; height: 148px;" >
														<MeImage   :src="item.posterUrl" width="148px" height="148px" radius="5"></MeImage >
													</view>
												</template>
												<template v-else>
													<view class="relative solid-border-gray91 radius-10" style="width: 148px; height: 148px">
														<text class="iconfont icon-zanwutupian absolute" style="color: #E8E8E8; font-size: 58px; top: 39px; left: 49px"></text> 
													</view>
												</template>
											</view>
										</view>
										<view class="flex-col margin-tb-5 w100">
											<text class="text-bold ">专辑</text>
											<view class="flex-row flex-wrap margin-tb-10">
												<template v-for="(album, index ) in item.albumUrls">
													<view class="margin-tb-5 " style="margin-left: 5px;" :style="albumStyle" @click="previewImage(item.albumUrls, index)">
														<MeImage  :src="album" :width="w1" :height="w1" radius="5"></MeImage >
													</view>
												</template>
											</view>
										</view>
										<view class="flex-row margin-tb-5 w100">
											<text class="text-bold ">审核状态:</text>
											<view class="margin-left-10">
												<text v-if="item.status == 0" class="text-gray41">初始化</text>
												<text v-else-if="item.status == 1" class="text-keyblue">机器审核通过</text>
												<text v-else-if="item.status == 2" class="text-red">机器审核不通</text>
												<text v-else-if="item.status == 4" class="text-red">人工审核不通过</text>
												<text v-else-if="item.status == 7" class="text-green">最终审核通过</text> 
												<text v-else class="text-pink">未知状态</text>
											</view>
										</view>
										<view class="margin-tb-5 w100" >
											<text class="text-bold ">审核备注:</text>
											<text class="margin-left-10 text-gray">{{item.remark}}</text>
										</view>
										<view class="margin-tb-5 w100" >
											<text class="text-bold ">代理商ID:</text>
											<text class="margin-left-10">{{item.referrerId}}</text>
										</view>
										<view class=" margin-tb-5" >
											<text class="text-bold">创建时间:</text>
											<text class="margin-left-10">{{ item.createTime }}</text>
										</view>
										<template v-if="item.updateTime">
											<view class=" margin-tb-5" >
												<text class="text-bold">更新时间:</text>
												<text class="margin-left-10">{{ item.updateTime }}</text>
											</view>
										</template>
										<view class="margin-top-32 flex-row" >
											<button class="cu-btn line-gray"  @click="flushOne(item.userId, item.applyCode)">
												<text>刷新</text>
												<text class="iconfont icon-shuaxin margin-left-10"></text> 
											</button>
											<template v-if="item.status != 7">
												<button class="cu-btn line-green margin-lr-10 "  @click="auditPassModel(item.userId, item.applyCode, true)">
													<text>审核</text>
													<text class="iconfont icon-shenqingtongguo margin-left-10"></text> 
												</button>
											</template>
											<button v-if="item.status != 7" class="cu-btn line-red margin-lr-10" @click="auditPassModel(item.userId, item.applyCode, false)">
												<text>审核</text>
												<text class="iconfont icon-shenqingjujue margin-left-10"></text> 
											</button>
										</view>
									</view>
								</view>
							</template>
						</view>
						<view v-if="!loadding" class="h600 flex-col align-center">
							<view class="h64"></view>
							<button class="cu-btn line-blue" :disabled="dataList.length >= query.totalSize" @click="nextPage">加载更多数据</button>
						</view>
					</template>
					<!-- 暂无数据 -->
					<template v-else>
                        <view v-if="!loadding" class="h300 w100 flex-col-center text-gray81">
							<text class="iconfont icon-zanwushuju2" style="font-size: 125px;"></text>
						</view>
					</template>
				</view>
			</template>
		</ScrollPage>
		<!-- 审核通过 -->
		<view class="cu-modal" :class="isShowPassModel ? 'show' : '' ">
			<view class="cu-dialog bg-white">
				<view class="padding-25 font-s38 text-black">
					<text>确定提示</text>
				</view>
				<view class="padding-25 text-green">
					确定该用户通过最终审核?
				</view>
				<view class="padding-25 flex-row justify-end w100">
					<button class="cu-btn line-grey margin-lr-10" @click="hideModal">取消</button>
					<button class="cu-btn line-blue margin-lr-10" @click="confirmPassAudit">确定</button>
				</view>
			</view>
		</view>
		<!-- 审核不通过 -->
		<view class="cu-modal" :class="isShowNoPassModel ? 'show' : '' ">
			<view class="cu-dialog bg-white">
				<view class="padding-25 font-s38 text-red">
					<text>确定审核未通过</text>
				</view>
				<view class="padding-25 text-green text-left">
					<up-textarea v-model="auditForm.cause" placeholder="请输入未通过原因" ></up-textarea>
				</view>
				<view class="padding-25 flex-row justify-end w100">
					<button class="cu-btn line-grey margin-lr-10" @click="hideModal">取消</button>
					<button class="cu-btn line-blue margin-lr-10" @click="confirmPassAudit">确定</button>
				</view>
			</view>
		</view>
        <up-datetime-picker ref="datePicker"  :formatter="formatter"    :show="showDatetime"  @cancel="cancelPicker" v-model="dataPickerValue"  
	   					cancelColor="red" @confirm="confirmSelectDate" mode="date"></up-datetime-picker>

		<up-picker v-model:show="statusShowPicker" v-model="statusSelected" :columns="statusColums" 
		  @confirm="statusConfirm" @cancel="statusCancel" keyName="label" valueName="value"></up-picker>					
	</view>
</template>
<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app"
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { previewSingleImage, previewImage  } from '@/utils/img'
import { formatter, convertDateFormat } from '@/utils/util'
import { navigate } from "@/security/router"
import { textToUrlCode } from "@/utils/strUtil"
import { urls } from "@/security/paths"
import { showError, showToast } from '@/utils/msg-show'
import { getOneApi, auditApi } from "@/api/anchor/apply"
import { useAnchorApplyStore } from '@/store'
import ScrollPage from "@/components/ScrollPage/ScrollPage.vue"

const anchorApplyStore = useAnchorApplyStore()
const { query, dataList } = storeToRefs(anchorApplyStore)

const loadding = ref(false)
const isShowPassModel = ref(false)
const isShowNoPassModel = ref(false)

const datePicker = ref()
const showDatetime = ref(false)
const today = new Date()
const dataPickerValue = ref(today.getTime())

const windowInfo = uni.getWindowInfo()
const screenWidth = windowInfo.screenWidth

const statusSelected = ref([0])
const statusSelectedName = ref()
const statusShowPicker = ref(false)
const statusColums = reactive([
	[
		{ label: "初始化", value: 0 },
		{ label: "机器审核通过", value: 1 },
		{ label: "机器审核不通", value: 2 },
		{ label: "人工审核不通过", value: 4 },
		{ label: "最终审核通过", value: 7 },
	]
])
const auditForm = reactive<any>({
	userId: "",
	applyCode: "",
	status: 1,
	cause: ""
})

// 屏幕宽度 - 已经消耗屏幕宽度
const w = screenWidth -  (5 + 5) - 48 - 10
const w1 = Math.floor( (w - 15) / 3)  + "px"
const albumStyle = reactive<any>({
	width: w1 
})

// 跳转到播放视频
function toPlay(videoUrl: string, posterUrl: string){
  navigate(`${urls.Play}?videoUrl=${textToUrlCode(videoUrl)}&posterUrl=${textToUrlCode(posterUrl)}`)
}

// 确定选择日期
function confirmSelectDate(val: any){
	const timestamp = val.value
    const date = new Date(timestamp)
    query.value.date = convertDateFormat(date)
	// animation	是否需要动画效果，仅小程序支持
	uni.showTabBar({
		animation:true,
		success: ()=>{
              showDatetime.value = false
		}
	})
}

// 状态显示
function statusShow(){
	uni.hideTabBar({
		animation:true,
		success: ()=>{
           statusShowPicker.value = true
		}
	})
}

// 确定选择状态
function statusConfirm(opt: any){
	uni.showTabBar({
		animation:true,
		success: ()=>{
			statusSelectedName.value = opt.value[0].label
			query.value.status = opt.value[0].value
			statusShowPicker.value = false
		}
	})
}

// 状态隐藏
function statusCancel(){
	uni.showTabBar({
		animation:true,
		success: ()=>{
           statusShowPicker.value = false
		}
	})
}

// 显示审核模态框
function auditPassModel(userId: string, applyCode: string, isPass: boolean){
    const target = dataList.value.find(e => e.userId === userId && e.applyCode === applyCode)
	if(target){
		if(isPass){
			isShowPassModel.value = true
		}else{
			isShowNoPassModel.value = true
		}
		auditForm.userId = userId
		auditForm.applyCode = applyCode
		auditForm.status = 1
	}
}

// 隐藏模态框
function hideModal(){
	isShowPassModel.value = false
	isShowNoPassModel.value = false
}

// 显示picker
function showPicker(){
    uni.hideTabBar({
		animation:true,
		success: ()=>{
            showDatetime.value = true
		}
	})
}

// 取消picker窗口
function cancelPicker(){
  	uni.showTabBar({
		animation:true,
		success: ()=>{
			showDatetime.value = false
		}
	})
}

// 确定通过审核
async function confirmPassAudit(){
	uni.showLoading({mask: true})
	await auditApi(auditForm).then((res:any) => {
		showToast("任务已提交,请稍后查看")
	}).catch(err => {
		showError(err.msg || err.errMsg || err)
	}).finally(()=>{
      uni.hideLoading()
	  hideModal()
   })
	
}

// 刷新单条数据
async function flushOne(userId: string, applyCode: string){
	const index = dataList.value.findIndex(e => e.userId === userId && e.applyCode === applyCode)
	if(index != -1 ){
		uni.showLoading({mask: true})
		await getOneApi({userId, applyCode}).then((res:any) => {
			dataList.value[index] = res.data
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		}).finally(()=>{
			uni.hideLoading()
		})
	}
}

// 确定搜索
async function confirmSearch(){
	dataList.value = []
    query.value.pageNum = 1
	await search()
}

// 下一页
async function nextPage(){
	if(dataList.value.length < query.value.totalSize){
		query.value.pageNum = query.value.pageNum + 1
		await search()
	}
}

// 搜索
async function search(){
	query.value.totalSize = undefined
	uni.showLoading({mask: true})
	loadding.value = true	
	await anchorApplyStore.getPage().finally(()=>{
		uni.hideLoading()
		loadding.value = false
	})
}

// 清空搜索条件
function searchClean(){
	query.value.nickname = ''
	query.value.date = ''
	query.value.status = undefined
	statusSelectedName.value = ''
	confirmSearch()
}

onLoad( async () => {
   loadding.value = true	
   uni.showLoading({mask: true})
   anchorApplyStore.init().finally(()=>{
      uni.hideLoading()
	  loadding.value = false
   })
});
</script>
